package com.learn.algorithm.realize;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * @author wangxing
 * @version 2020/7/9 8:10 Administrator
 */
public class LRULinkedHashMap implements ILRU {
    private int capacity = 0;

    private class Node {
        String key;
        String val;

        public Node(String key, String val) {
            this.key = key;
            this.val = val;
        }
    }

    private LinkedHashMap<String, String> cache;

    public LRULinkedHashMap(int capacity) {
        this.capacity = capacity;
        this.cache = new LinkedHashMap<>((int) (capacity / 0.75));
    }

    /**
     * 返回最少使用内容
     *
     * @param key
     * @return
     */
    @Override
    public String get(String key) {
        String result = null;
        if (this.cache.containsKey(key)) {
            result = cache.get(key);
            cache.remove(key);
            cache.put(key, result);
        }
        return result;
    }

    /**
     * 存入算法
     *
     * @param key
     * @param val
     */
    @Override
    public void put(String key, String val) {
        if (this.cache.containsKey(key)) {
            this.cache.remove(key);
        }
        if (this.cache.size() == this.capacity) {
            Set<String> set = this.cache.keySet();
            Iterator<String> iterator = set.iterator();
            cache.remove(iterator.next());
        }
        this.cache.put(key, val);
    }
}
